﻿using Castle.MonoRail.Framework;
using MyMessenger.Core;
using MyMessenger.Core.Services;
using MyMessenger.Web.Filters;

namespace MyMessenger.Web.Controllers
{
    [Layout("default"), Rescue("generalerror")]
    [Filter(ExecuteEnum.BeforeAction, typeof(AuthenticationFilter), ExecutionOrder = 1)]
    public class MessegeController : SmartDispatcherController
    {
        private IMessageService service;
        private IUserService userService;

        protected User CurrentUser
        {
            get { return (User)Context.CurrentUser;}
        }

        public MessegeController(IMessageService service, IUserService userService)
        {
            this.service = service;
            this.userService = userService;
        }

        public void Index()
        {
            Messege[] list = service.GetAllMessagesToUser(CurrentUser);
            PropertyBag["messeges"] = list;
            PropertyBag["lastMessegeId"] = GetLastId(list);
            PropertyBag["users"] = userService.ActiveUsers();
        }

        public void GetNewMesseges(int lastMessegeId)
        {
            Messege[] list = service.GetNewMessages(CurrentUser, lastMessegeId);
            PropertyBag["messeges"] = list;
            PropertyBag["lastMessegeId"] = GetLastId(list) == 0 ? lastMessegeId : GetLastId(list);
            PropertyBag["users"] = userService.ActiveUsers();
        }

        private static int GetLastId(Messege[] list)
        {
            if (list.Length > 0)
                return list[list.Length - 1].Id;
            else
                return 0;
        }


        public void AddMessege(string messege)
        {
            service.AddMessage(CurrentUser, null, messege);
            CancelView();
        }
    }
}
